package com.hwpt.chesedemo.presentation.viewmodel

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hwpt.chesedemo.data.remote.api.ApiClient
import com.hwpt.chesedemo.data.local.repository.ChessRepository
import com.hwpt.chesedemo.data.remote.util.ChessUtils
import com.hwpt.chesedemo.presentation.component.ChessMove
import com.hwpt.chesedemo.presentation.component.ChessPiece
import com.hwpt.chesedemo.presentation.component.ChessScreen
import com.hwpt.chesedemo.presentation.component.Difficulty
import com.hwpt.chesedemo.presentation.component.GameResult
import com.hwpt.chesedemo.presentation.component.GameState
import com.hwpt.chesedemo.presentation.component.GameStatus
import com.hwpt.chesedemo.presentation.component.PieceType
import com.hwpt.chesedemo.presentation.component.Player
import com.hwpt.chesedemo.presentation.component.Position
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import java.io.IOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import javax.inject.Inject

@HiltViewModel
class ChessGameViewModel @Inject constructor(
    private val chessRepository: ChessRepository,
    @ApplicationContext private val appContext: Context, // 应用级Context（推荐，无内存泄漏）
) : ViewModel() {
    // 添加高亮移动状态
    private var lastBlackMove: Pair<Position, Position>? = null

    private val _gameState = MutableStateFlow(GameState())
    val gameState: StateFlow<GameState> = _gameState

    private val coroutineScope = CoroutineScope(Dispatchers.Main)
    private var aiThinkingJob: Job? = null

    // 游戏状态跟踪
    private var enPassantTarget: Position? = null
    private var halfMoveClock = 0
    private var fullMoveNumber = 1

    // 悔棋功能相关状态 - 保存完整的游戏历史
    private val gameHistoryStack = mutableListOf<GameSnapshot>()

    // 王车易位状态 - 统一使用castlingRights映射
    private val castlingRights = mutableMapOf(
        "whiteKingside" to true,
        "whiteQueenside" to true,
        "blackKingside" to true,
        "blackQueenside" to true
    )

    init {
        // 初始化时保存初始状态
        saveCurrentGameState()
    }

    fun selectDifficulty(difficulty: Difficulty) {
        resetGameState()
        _gameState.update { state ->
            state.copy(
                selectedDifficulty = difficulty,
                currentScreen = ChessScreen.GAME_BOARD,
                currentTurn = Player.WHITE,
                boardState = initialBoardState(),
                moveCount = 0,
                moveHistory = emptyList(),
                gameStatus = GameStatus.IN_PROGRESS,
                showGameOverDialog = false,
                gameResult = null,
                highlightedMove = null // 重置高亮移动
            )
        }
        // 清空悔棋历史
        gameHistoryStack.clear()
        // 保存初始状态
        saveCurrentGameState()
    }

    fun selectPiece(position: Position) {
        _gameState.update { state ->
            if (state.currentTurn != Player.WHITE) {
                return@update state
            }

            val piece = state.boardState[position.row][position.col]

            if (state.selectedPiece != null) {
                val isValidMove =
                    state.validMoves.any { it.row == position.row && it.col == position.col }
                if (isValidMove) {
                    makeMove(state.selectedPiece!!, position)
                    return@update state.copy(selectedPiece = null, validMoves = emptyList())
                } else {
                    return@update state.copy(selectedPiece = null, validMoves = emptyList())
                }
            }

            if (piece != null && piece.player == Player.WHITE) {
                val validMoves = calculateValidMoves(piece, state.boardState)
                state.copy(
                    selectedPiece = position,
                    validMoves = validMoves
                )
            } else {
                state.copy(selectedPiece = null, validMoves = emptyList())
            }
        }
    }

    fun makeMove(from: Position, to: Position) {
        // 在移动前保存状态
        saveCurrentGameState()

        _gameState.update { state ->
            try {
                val newBoard = state.boardState.map { it.toMutableList() }.toMutableList()
                val piece = newBoard[from.row][from.col]

                if (piece != null && piece.player == state.currentTurn) {
                    val moveResult = performMove(
                        newBoard, from, to, piece
                    )

                    // 更新游戏状态
                    enPassantTarget = moveResult.enPassantTarget

                    // 更新50步规则计数器
                    if (piece.type == PieceType.PAWN || moveResult.isCapture) {
                        halfMoveClock = 0
                    } else {
                        halfMoveClock++
                    }

                    val newMoveCount = state.moveCount + 1
                    val newTurn = if (state.currentTurn == Player.WHITE) Player.BLACK else Player.WHITE

                    // 更新完整回合数
                    if (newTurn == Player.WHITE) {
                        fullMoveNumber++
                    }

                    val capturedPiece = state.boardState[to.row][to.col]
                    val isCapture = capturedPiece != null
                    val moveNotation = getAlgebraicNotation(
                        piece, from, to, state.boardState, isCapture
                    )

                    val newMoveHistory = updateMoveHistory(
                        state.moveHistory,
                        moveNotation,
                        state.currentTurn,
                        newMoveCount
                    )

                    // 检查是否吃王
                    val newGameStatus = if (moveResult.isKingCaptured) {
                        GameStatus.CHECKMATE
                    } else {
                        checkGameStatus(newBoard, newTurn, halfMoveClock)
                    }

                    val showGameOver = newGameStatus != GameStatus.IN_PROGRESS && newGameStatus != GameStatus.CHECK

                    // 设置高亮标记：如果是黑棋移动，记录移动；如果是白棋移动，清除高亮
                    val newHighlightedMove = if (state.currentTurn == Player.BLACK) {
                        // 黑棋移动，记录移动用于高亮
                        Pair(from, to)
                    } else {
                        // 白棋移动，清除高亮
                        null
                    }

                    val newState = state.copy(
                        boardState = newBoard,
                        currentTurn = newTurn,
                        moveCount = newMoveCount,
                        moveHistory = newMoveHistory,
                        selectedPiece = null,
                        validMoves = emptyList(),
                        gameStatus = newGameStatus,
                        showGameOverDialog = showGameOver,
                        gameResult = if (showGameOver) createGameResult(
                            newGameStatus,
                            newTurn,
                            moveResult.isKingCaptured
                        ) else null,
                        highlightedMove = newHighlightedMove // 更新高亮移动
                    )

                    // 显示将军提示
                    if (newGameStatus == GameStatus.CHECK) {
                        showCheckMessage(newTurn)
                    }

                    if (!showGameOver && newTurn == Player.BLACK) {
                        startAiThinking()
                    }

                    newState
                } else {
                    state
                }
            } catch (e: Exception) {
                e.printStackTrace()
                state
            }
        }

        // 玩家移动后保存状态
        saveCurrentGameState()
    }

    // ========== 修复后的悔棋功能 ==========
    fun undoMove() {
        // 只有白方回合才能悔棋
        if (gameState.value.currentTurn != Player.WHITE) {
            showToast("只能在白方回合悔棋")
            return
        }

        if (aiThinkingJob?.isActive == true) {
            showToast("AI正在思考，请稍后")
            return
        }

        // 需要至少3个状态：初始状态 + 白棋移动 + 黑棋移动
        if (gameHistoryStack.size < 3) {
            showToast("没有可以悔棋的完整回合")
            return
        }

        // 取消AI思考
        aiThinkingJob?.cancel()

        // 移除2个状态：黑棋移动后的状态 + 白棋移动后的状态
        // 回到白棋移动前的状态
        gameHistoryStack.removeAt(gameHistoryStack.size - 1) // 移除黑棋移动后的状态
        gameHistoryStack.removeAt(gameHistoryStack.size - 1) // 移除白棋移动后的状态

        // 恢复到上一个状态（白棋移动前的状态）
        if (gameHistoryStack.isNotEmpty()) {
            val snapshot = gameHistoryStack.last()
            restoreGameStateFromSnapshot(snapshot)
            showToast("悔棋成功：已回退一个完整回合")
        } else {
            resetToInitialState()
            showToast("已回到游戏开始")
        }
    }

    private fun restoreGameStateFromSnapshot(snapshot: GameSnapshot) {
        _gameState.update { state ->
            state.copy(
                boardState = snapshot.boardState,
                currentTurn = snapshot.currentTurn,
                moveCount = snapshot.moveCount,
                moveHistory = snapshot.moveHistory,
                selectedPiece = null,
                validMoves = emptyList(),
                gameStatus = snapshot.gameStatus,
                showGameOverDialog = false,
                gameResult = null,
                highlightedMove = snapshot.highlightedMove // 恢复高亮移动状态
            )
        }

        // 恢复游戏状态
        enPassantTarget = snapshot.enPassantTarget
        halfMoveClock = snapshot.halfMoveClock
        fullMoveNumber = snapshot.fullMoveNumber

        // 恢复王车易位权利
        castlingRights["whiteKingside"] = snapshot.castlingWhiteKingside
        castlingRights["whiteQueenside"] = snapshot.castlingWhiteQueenside
        castlingRights["blackKingside"] = snapshot.castlingBlackKingside
        castlingRights["blackQueenside"] = snapshot.castlingBlackQueenside
    }

    private fun resetToInitialState() {
        resetGameState()
        _gameState.update { state ->
            state.copy(
                boardState = initialBoardState(),
                currentTurn = Player.WHITE,
                moveCount = 0,
                moveHistory = emptyList(),
                selectedPiece = null,
                validMoves = emptyList(),
                gameStatus = GameStatus.IN_PROGRESS,
                showGameOverDialog = false,
                gameResult = null,
                highlightedMove = null // 重置高亮移动
            )
        }
    }

    private fun saveCurrentGameState() {
        val state = _gameState.value

        // 避免重复保存相同状态
        if (gameHistoryStack.isNotEmpty()) {
            val lastSnapshot = gameHistoryStack.last()
            if (lastSnapshot.boardState == state.boardState &&
                lastSnapshot.currentTurn == state.currentTurn) {
                Log.d("ChessGameViewModel", "跳过重复状态保存")
                return
            }
        }

        val snapshot = GameSnapshot(
            boardState = state.boardState.map { it.toList() }.toList(),
            currentTurn = state.currentTurn,
            moveCount = state.moveCount,
            moveHistory = state.moveHistory.toList(),
            gameStatus = state.gameStatus,
            enPassantTarget = enPassantTarget,
            halfMoveClock = halfMoveClock,
            fullMoveNumber = fullMoveNumber,
            castlingWhiteKingside = castlingRights["whiteKingside"] ?: false,
            castlingWhiteQueenside = castlingRights["whiteQueenside"] ?: false,
            castlingBlackKingside = castlingRights["blackKingside"] ?: false,
            castlingBlackQueenside = castlingRights["blackQueenside"] ?: false,
            highlightedMove = state.highlightedMove // 保存高亮移动状态
        )

        gameHistoryStack.add(snapshot)
        Log.d("ChessGameViewModel", "保存游戏状态，当前历史记录数: ${gameHistoryStack.size}, 当前回合: ${state.currentTurn}")
    }

    fun canUndo(): Boolean {
        // 只有在白方回合且历史记录足够时才能悔棋
        return gameState.value.currentTurn == Player.WHITE &&
                gameHistoryStack.size >= 3 &&
                aiThinkingJob?.isActive != true
    }

    // 获取当前可以悔棋的完整回合数
    fun getAvailableUndoCount(): Int {
        // 总状态数 - 1（初始状态）然后除以2（每个完整回合需要2个状态）
        return if (gameHistoryStack.size >= 3) {
            (gameHistoryStack.size - 1) / 2
        } else {
            0
        }
    }

    private fun showToast(message: String) {
        coroutineScope.launch {
            Toast.makeText(appContext, message, Toast.LENGTH_SHORT).show()
        }
    }

    fun resign() {
        aiThinkingJob?.cancel()
        _gameState.update { state ->
            val winner = if (state.currentTurn == Player.WHITE) Player.BLACK else Player.WHITE
            state.copy(
                showGameOverDialog = true,
                gameStatus = GameStatus.RESIGNED,
                gameResult = GameResult(
                    title = "认输",
                    message = "${if (state.currentTurn == Player.WHITE) "白方" else "黑方"}认输，${if (winner == Player.WHITE) "白方" else "黑方"}获胜！",
                    winner = winner
                )
            )
        }
    }

    fun requestDraw() {
        aiThinkingJob?.cancel()
        _gameState.update { state ->
            state.copy(
                showGameOverDialog = true,
                gameStatus = GameStatus.DRAW,
                gameResult = GameResult(
                    title = "和棋",
                    message = "游戏以和棋结束！"
                )
            )
        }
    }

    fun saveGame() {
        viewModelScope.launch {
            chessRepository.saveGame(_gameState.value)  // 传递当前游戏状态
        }
    }

    fun newGame() {
        aiThinkingJob?.cancel()
        resetGameState()
        gameHistoryStack.clear()
        _gameState.value = GameState()
        // 保存初始状态
        saveCurrentGameState()
    }

    fun acknowledgeGameOver() {
        aiThinkingJob?.cancel()
        _gameState.update { it.copy(showGameOverDialog = false) }
    }

    // ========== AI 移动执行 ==========
    private suspend fun executeAiMove(
        gameState: GameState,
        onMoveExecuted: (Position, Position) -> Unit,
        onError: (String) -> Unit
    ) {
        var retryCount = 0
        val maxRetries = 2

        while (retryCount <= maxRetries) {
            try {
                if (gameState.currentTurn != Player.BLACK ||
                    (gameState.gameStatus != GameStatus.IN_PROGRESS &&
                            gameState.gameStatus != GameStatus.CHECK)) {
                    return
                }

                val fen = generateFEN(
                    gameState.boardState,
                    Player.BLACK,
                    gameState.selectedDifficulty?.aiLevel ?: 2
                )
                val depth = ChessUtils.getAiDepth(gameState.selectedDifficulty?.aiLevel ?: 2)

                val response = ApiClient.stockfishApi.getBestMove(fen, depth)

                if (response.isSuccessful) {
                    val stockfishResponse = response.body()
                    if (stockfishResponse?.success == true && !stockfishResponse.bestmove.isNullOrEmpty()) {
                        val bestMove = stockfishResponse.bestmove
                        val move = parseAlgebraicMove(bestMove, gameState.boardState, Player.BLACK)
                        if (move != null) {
                            onMoveExecuted(move.first, move.second)
                            return
                        } else {
                            throw IOException("Failed to parse move from Stockfish")
                        }
                    } else {
                        throw IOException("Stockfish API returned failure: ${response.message()}")
                    }
                } else {
                    throw IOException("API call failed with code: ${response.code()}, message: ${response.message()}")
                }

            } catch (e: Exception) {
                retryCount++
                if (retryCount > maxRetries) {
                    val errorMsg = when (e) {
                        is SocketTimeoutException -> "AI连接超时，请检查网络"
                        is ConnectException -> "无法连接AI服务器，请稍后再试"
                        else -> "调用失败：请检查网络"
                    }
                    onError(errorMsg)
                    e.printStackTrace()
                    return
                }
                withContext(Dispatchers.IO) { delay(1000) }
            }
        }
    }

    private fun generateFEN(board: List<List<ChessPiece?>>, currentTurn: Player, aiLevel: Int): String {
        val fenBuilder = StringBuilder()

        // 棋子位置
        for (row in 0 until 8) {
            var emptyCount = 0
            for (col in 0 until 8) {
                val piece = board[row][col]
                if (piece == null) {
                    emptyCount++
                } else {
                    if (emptyCount > 0) {
                        fenBuilder.append(emptyCount)
                        emptyCount = 0
                    }
                    fenBuilder.append(piece.toFENSymbol())
                }
            }
            if (emptyCount > 0) {
                fenBuilder.append(emptyCount)
            }
            if (row < 7) {
                fenBuilder.append('/')
            }
        }

        // 当前回合
        fenBuilder.append(" ${if (currentTurn == Player.WHITE) 'w' else 'b'} ")

        // 王车易位权利
        val castling = StringBuilder()
        if (castlingRights["whiteKingside"] == true) castling.append('K')
        if (castlingRights["whiteQueenside"] == true) castling.append('Q')
        if (castlingRights["blackKingside"] == true) castling.append('k')
        if (castlingRights["blackQueenside"] == true) castling.append('q')
        if (castling.isEmpty()) castling.append('-')
        fenBuilder.append("$castling ")

        // 吃过路兵目标
        fenBuilder.append("${enPassantTarget?.let { "${getFileLetter(it.col)}${8 - it.row}" } ?: "-"} ")

        // 半回合计数和完整回合数
        fenBuilder.append("$halfMoveClock $fullMoveNumber")

        return fenBuilder.toString()
    }

    private fun parseAlgebraicMove(
        move: String,
        board: List<List<ChessPiece?>>,
        player: Player
    ): Pair<Position, Position>? {
        val cleanMove = move.trim()

        if (cleanMove == "O-O" || cleanMove == "0-0") {
            val row = if (player == Player.WHITE) 7 else 0
            return Pair(Position(row, 4), Position(row, 6))
        }
        if (cleanMove == "O-O-O" || cleanMove == "0-0-0") {
            val row = if (player == Player.WHITE) 7 else 0
            return Pair(Position(row, 4), Position(row, 2))
        }

        return ChessUtils.parseStockfishMove(cleanMove)
    }

    // 扩展函数 - 棋子转FEN符号
    private fun ChessPiece.toFENSymbol(): Char {
        val symbol = when (type) {
            PieceType.KING -> 'k'
            PieceType.QUEEN -> 'q'
            PieceType.ROOK -> 'r'
            PieceType.BISHOP -> 'b'
            PieceType.KNIGHT -> 'n'
            PieceType.PAWN -> 'p'
        }
        return if (player == Player.WHITE) symbol.uppercaseChar() else symbol
    }

    // ========== 游戏状态管理 ==========
    private fun startAiThinking() {
        aiThinkingJob = coroutineScope.launch {
            delay(300)
            executeAiMove(
                _gameState.value,
                onMoveExecuted = { from, to -> executeAiMove(from, to) },
                onError = { errorMessage -> handleAiError(errorMessage) }
            )
        }
    }

    private fun executeAiMove(from: Position, to: Position) {
        _gameState.update { state ->
            val newBoard = state.boardState.map { it.toMutableList() }.toMutableList()
            val piece = newBoard[from.row][from.col]

            if (piece == null) {
                Log.e("ChessGameViewModel", "AI移动错误：位置(${from.row}, ${from.col})没有棋子")
                return@update state
            }

            val moveResult = performMove(newBoard, from, to, piece)
            enPassantTarget = moveResult.enPassantTarget

            if (piece.type == PieceType.PAWN || moveResult.isCapture) {
                halfMoveClock = 0
            } else {
                halfMoveClock++
            }

            val newMoveCount = state.moveCount + 1
            val newTurn = Player.WHITE
            fullMoveNumber++

            val capturedPiece = state.boardState[to.row][to.col]
            val isCapture = capturedPiece != null
            val moveNotation = getAlgebraicNotation(
                piece, from, to, state.boardState, isCapture
            )

            val newMoveHistory = updateMoveHistory(
                state.moveHistory,
                moveNotation,
                Player.BLACK,
                newMoveCount
            )

            val newGameStatus = if (moveResult.isKingCaptured) {
                GameStatus.CHECKMATE
            } else {
                checkGameStatus(newBoard, newTurn, halfMoveClock)
            }
            val showGameOver = newGameStatus != GameStatus.IN_PROGRESS && newGameStatus != GameStatus.CHECK

            // 关键修复：确保AI移动后设置高亮
            val newHighlightedMove = Pair(from, to)

            if (newGameStatus == GameStatus.CHECK) {
                showCheckMessage(newTurn)
            }

            state.copy(
                boardState = newBoard,
                currentTurn = newTurn,
                moveCount = newMoveCount,
                moveHistory = newMoveHistory,
                gameStatus = newGameStatus,
                showGameOverDialog = showGameOver,
                gameResult = if (showGameOver) createGameResult(newGameStatus, newTurn, moveResult.isKingCaptured) else null,
                highlightedMove = newHighlightedMove // 确保这里设置高亮
            )
        }

        // AI移动后保存状态
        saveCurrentGameState()
    }

    private fun handleAiError(errorMessage: String) {
        _gameState.update { state ->
            state.copy(
                showGameOverDialog = true,
                gameStatus = GameStatus.RESIGNED,
                gameResult = GameResult(
                    title = "AI错误",
                    message = "$errorMessage\n游戏结束，玩家获胜！",
                    winner = Player.WHITE
                )
            )
        }
    }

    private fun showCheckMessage(playerInCheck: Player) {
        coroutineScope.launch {
            Toast.makeText(
                appContext,
                "${if (playerInCheck == Player.WHITE) "白方" else "黑方"}被将军！",
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    private fun updateMoveHistory(
        currentHistory: List<ChessMove>,
        moveNotation: String,
        currentPlayer: Player,
        moveCount: Int
    ): List<ChessMove> {
        val newHistory = currentHistory.toMutableList()
        val moveNumber = (moveCount + 1) / 2

        if (currentPlayer == Player.WHITE) {
            newHistory.add(ChessMove(moveNumber, whiteMove = moveNotation))
        } else {
            if (newHistory.isNotEmpty() && newHistory.last().blackMove == null) {
                val lastMove = newHistory.last()
                newHistory[newHistory.lastIndex] = lastMove.copy(blackMove = moveNotation)
            } else {
                newHistory.add(ChessMove(moveNumber, blackMove = moveNotation))
            }
        }

        return newHistory
    }

    private fun createGameResult(status: GameStatus, currentTurn: Player, isKingCaptured: Boolean = false): GameResult {
        return when {
            isKingCaptured -> {
                // 吃王的情况
                val winner = currentTurn // 吃王的一方获胜
                val loser = if (winner == Player.WHITE) Player.BLACK else Player.WHITE
                GameResult(
                    title = "吃王获胜！",
                    message = "${if (winner == Player.WHITE) "白方" else "黑方"}吃掉了${if (loser == Player.WHITE) "白方" else "黑方"}的王，游戏结束！",
                    winner = winner
                )
            }
            status == GameStatus.CHECKMATE -> {
                val loser = currentTurn
                val winner = if (loser == Player.WHITE) Player.BLACK else Player.WHITE
                GameResult(
                    title = "将死！",
                    message = "${if (winner == Player.WHITE) "白方" else "黑方"}获胜！\n${if (loser == Player.WHITE) "白方" else "黑方"}被将死且无路可走。",
                    winner = winner
                )
            }
            status == GameStatus.STALEMATE -> {
                GameResult(
                    title = "僵局",
                    message = "游戏以和棋结束\n${if (currentTurn == Player.WHITE) "白方" else "黑方"}无合法移动但未被将军。"
                )
            }
            status == GameStatus.RESIGNED -> {
                val winner = if (currentTurn == Player.WHITE) Player.BLACK else Player.WHITE
                GameResult(
                    title = "认输",
                    message = "${if (currentTurn == Player.WHITE) "白方" else "黑方"}认输，${if (winner == Player.WHITE) "白方" else "黑方"}获胜！",
                    winner = winner
                )
            }
            status == GameStatus.DRAW -> GameResult(
                title = "和棋",
                message = "游戏以和棋结束\n根据50步规则，双方在50步内没有吃子且没有兵移动。"
            )
            else -> GameResult(
                title = "游戏结束",
                message = "游戏已结束"
            )
        }
    }

    private fun resetGameState() {
        enPassantTarget = null
        halfMoveClock = 0
        fullMoveNumber = 1

        // 重置王车易位权利
        castlingRights["whiteKingside"] = true
        castlingRights["whiteQueenside"] = true
        castlingRights["blackKingside"] = true
        castlingRights["blackQueenside"] = true
    }

    // ========== 游戏状态检查 ==========
    private fun checkGameStatus(
        board: List<List<ChessPiece?>>,
        currentTurn: Player,
        halfMoveClock: Int
    ): GameStatus {
        // 检查50步规则
        if (halfMoveClock >= 100) {
            return GameStatus.DRAW
        }

        // 使用新的将死检查方法
        if (isCheckmate(currentTurn, board)) {
            return GameStatus.CHECKMATE
        }

        // 检查僵局
        if (!hasAnyLegalMoveToRemoveCheck(currentTurn, board) &&
            !isInCheck(currentTurn, board)) {
            return GameStatus.STALEMATE
        }

        // 检查将军状态
        if (isInCheck(currentTurn, board)) {
            return GameStatus.CHECK
        }

        return GameStatus.IN_PROGRESS
    }

    // ========== 移动计算 ==========
    private fun calculateValidMoves(
        piece: ChessPiece,
        board: List<List<ChessPiece?>>
    ): List<Position> {
        val player = piece.player
        val isPlayerInCheck = isInCheck(player, board)

        // 计算所有可能的移动
        val allPossibleMoves = when (piece.type) {
            PieceType.PAWN -> calculatePawnMoves(piece, board)
            PieceType.ROOK -> calculateRookMoves(piece, board)
            PieceType.KNIGHT -> calculateKnightMoves(piece, board)
            PieceType.BISHOP -> calculateBishopMoves(piece, board)
            PieceType.QUEEN -> calculateQueenMoves(piece, board)
            PieceType.KING -> calculateKingMoves(piece, board)
        }

        // 如果玩家没有被将军，返回所有合法移动
        if (!isPlayerInCheck) {
            return allPossibleMoves.filter { isValidMove(piece, it, board) }
        }

        // 如果玩家被将军，只允许解除将军的移动
        return allPossibleMoves.filter { move ->
            isValidMove(piece, move, board) && wouldRemoveCheck(piece, move, board)
        }
    }

    // 新增方法：检查移动是否会解除将军状态
    private fun wouldRemoveCheck(
        piece: ChessPiece,
        newPosition: Position,
        board: List<List<ChessPiece?>>
    ): Boolean {
        val tempBoard = board.map { it.toMutableList() }.toMutableList()

        // 执行移动
        tempBoard[newPosition.row][newPosition.col] = piece.copy(position = newPosition)
        tempBoard[piece.position.row][piece.position.col] = null

        // 检查移动后是否仍然被将军
        return !isInCheck(piece.player, tempBoard)
    }

    // 新增方法：检查玩家是否有任何可以解除将军的合法移动
    private fun hasAnyLegalMoveToRemoveCheck(player: Player, board: List<List<ChessPiece?>>): Boolean {
        // 遍历所有己方棋子
        for (row in 0 until 8) {
            for (col in 0 until 8) {
                val piece = board[row][col]
                if (piece != null && piece.player == player) {
                    // 计算该棋子的所有可能移动
                    val possibleMoves = when (piece.type) {
                        PieceType.PAWN -> calculatePawnMoves(piece, board)
                        PieceType.ROOK -> calculateRookMoves(piece, board)
                        PieceType.KNIGHT -> calculateKnightMoves(piece, board)
                        PieceType.BISHOP -> calculateBishopMoves(piece, board)
                        PieceType.QUEEN -> calculateQueenMoves(piece, board)
                        PieceType.KING -> calculateKingMoves(piece, board)
                    }

                    // 检查是否有任何一个移动可以解除将军
                    val hasRemovingMove = possibleMoves.any { move ->
                        isValidMove(piece, move, board) && wouldRemoveCheck(piece, move, board)
                    }

                    if (hasRemovingMove) {
                        return true
                    }
                }
            }
        }
        return false
    }

    // 新增方法：检查是否将死（被将军且无法解除）
    private fun isCheckmate(player: Player, board: List<List<ChessPiece?>>): Boolean {
        // 如果玩家没有被将军，肯定不是将死
        if (!isInCheck(player, board)) {
            return false
        }

        // 检查是否有任何可以解除将军的合法移动
        return !hasAnyLegalMoveToRemoveCheck(player, board)
    }

    private fun performMove(
        board: MutableList<MutableList<ChessPiece?>>,
        from: Position,
        to: Position,
        piece: ChessPiece
    ): MoveResult {
        var newEnPassantTarget: Position? = null

        // 检查是否吃子，并特别检查是否吃王
        val capturedPiece = board[to.row][to.col]
        val isCapture = capturedPiece != null
        val isKingCaptured = capturedPiece?.type == PieceType.KING // 新增：检测是否吃王

        // 处理王车易位
        if (piece.type == PieceType.KING && Math.abs(from.col - to.col) == 2) {
            // 执行易位移动
            handleCastling(board, from, to, piece.player)
            return MoveResult(
                enPassantTarget = newEnPassantTarget,
                isCapture = isCapture,
                isKingCaptured = isKingCaptured
            )
        }

        // 处理吃过路兵
        if (piece.type == PieceType.PAWN && from.col != to.col && !isCapture) {
            val enPassantRow = if (piece.player == Player.WHITE) to.row + 1 else to.row - 1
            board[enPassantRow][to.col] = null
        }

        // 设置吃过路兵目标
        newEnPassantTarget = if (piece.type == PieceType.PAWN && Math.abs(from.row - to.row) == 2) {
            val enPassantRow = if (piece.player == Player.WHITE) from.row - 1 else from.row + 1
            Position(enPassantRow, from.col)
        } else {
            null
        }

        // 处理兵升变
        val movedPiece = if (piece.type == PieceType.PAWN && (to.row == 0 || to.row == 7)) {
            piece.copy(type = PieceType.QUEEN, position = to)
        } else {
            piece.copy(position = to)
        }

        board[to.row][to.col] = movedPiece
        board[from.row][from.col] = null

        // 更新易位权利
        updateCastlingRightsAfterMove(piece)

        return MoveResult(
            enPassantTarget = newEnPassantTarget,
            isCapture = isCapture,
            isKingCaptured = isKingCaptured
        )
    }

    // ========== 修复王车移位执行逻辑 ==========
    private fun handleCastling(
        board: MutableList<MutableList<ChessPiece?>>,
        from: Position,
        to: Position,
        player: Player
    ) {
        val row = from.row

        when {
            // 短易位（王翼易位）
            to.col == 6 -> {
                val rookFromCol = 7
                val rookToCol = 5

                // 获取王和车
                val king = board[row][from.col]
                val rook = board[row][rookFromCol]

                // 验证棋子存在
                if (king == null || rook == null) return

                // 原子操作：同时清空原位置，设置新位置
                board[from.row][from.col] = null
                board[row][rookFromCol] = null

                board[to.row][to.col] = king.copy(position = to)
                board[row][rookToCol] = rook.copy(position = Position(row, rookToCol))

                // 更新易位权利
                updateCastlingRightsAfterMove(king)
                updateCastlingRightsAfterMove(rook)
            }
            // 长易位（后翼易位）
            to.col == 2 -> {
                val rookFromCol = 0
                val rookToCol = 3

                // 获取王和车
                val king = board[row][from.col]
                val rook = board[row][rookFromCol]

                // 验证棋子存在
                if (king == null || rook == null) return

                // 原子操作：同时清空原位置，设置新位置
                board[from.row][from.col] = null
                board[row][rookFromCol] = null

                board[to.row][to.col] = king.copy(position = to)
                board[row][rookToCol] = rook.copy(position = Position(row, rookToCol))

                // 更新易位权利
                updateCastlingRightsAfterMove(king)
                updateCastlingRightsAfterMove(rook)
            }
        }
    }


    // 新增方法：更新易位权利
    private fun updateCastlingRightsAfterMove(piece: ChessPiece) {
        when {
            piece.type == PieceType.KING -> {
                if (piece.player == Player.WHITE) {
                    castlingRights["whiteKingside"] = false
                    castlingRights["whiteQueenside"] = false
                } else {
                    castlingRights["blackKingside"] = false
                    castlingRights["blackQueenside"] = false
                }
            }
            piece.type == PieceType.ROOK -> {
                when {
                    piece.player == Player.WHITE && piece.position.col == 0 ->
                        castlingRights["whiteQueenside"] = false
                    piece.player == Player.WHITE && piece.position.col == 7 ->
                        castlingRights["whiteKingside"] = false
                    piece.player == Player.BLACK && piece.position.col == 0 ->
                        castlingRights["blackQueenside"] = false
                    piece.player == Player.BLACK && piece.position.col == 7 ->
                        castlingRights["blackKingside"] = false
                }
            }
        }
    }

    private fun getAlgebraicNotation(
        piece: ChessPiece,
        from: Position,
        to: Position,
        board: List<List<ChessPiece?>>,
        isCapture: Boolean
    ): String {
        return when (piece.type) {
            PieceType.KING -> {
                when {
                    from.col == 4 && to.col == 6 -> "O-O"
                    from.col == 4 && to.col == 2 -> "O-O-O"
                    else -> "K${getFileLetter(to.col)}${8 - to.row}"
                }
            }

            PieceType.PAWN -> {
                val fileLetter = getFileLetter(from.col)
                val captureNotation = if (isCapture) "${fileLetter}x" else ""
                val destination = "${getFileLetter(to.col)}${8 - to.row}"
                val promotion = if ((piece.player == Player.WHITE && to.row == 0) ||
                    (piece.player == Player.BLACK && to.row == 7)
                ) "=Q" else ""

                "$captureNotation$destination$promotion"
            }

            else -> {
                val pieceSymbol = when (piece.type) {
                    PieceType.ROOK -> "R"
                    PieceType.KNIGHT -> "N"
                    PieceType.BISHOP -> "B"
                    PieceType.QUEEN -> "Q"
                    else -> ""
                }

                val disambiguation = getDisambiguation(piece, from, to, board)
                val captureSymbol = if (isCapture) "x" else ""
                val destination = "${getFileLetter(to.col)}${8 - to.row}"

                "$pieceSymbol$disambiguation$captureSymbol$destination"
            }
        }
    }

    private fun calculatePawnMoves(
        pawn: ChessPiece,
        board: List<List<ChessPiece?>>
    ): List<Position> {
        val moves = mutableListOf<Position>()
        val direction = if (pawn.player == Player.WHITE) -1 else 1
        val startRow = if (pawn.player == Player.WHITE) 6 else 1

        // 前进一格
        val forwardOne = Position(pawn.position.row + direction, pawn.position.col)
        if (isValidPosition(forwardOne) && board[forwardOne.row][forwardOne.col] == null) {
            moves.add(forwardOne)

            // 前进两格（起始位置）
            if (pawn.position.row == startRow) {
                val forwardTwo = Position(pawn.position.row + 2 * direction, pawn.position.col)
                if (isValidPosition(forwardTwo) && board[forwardTwo.row][forwardTwo.col] == null) {
                    moves.add(forwardTwo)
                }
            }
        }

        // 吃子（包括吃过路兵）
        val captureMoves = listOf(
            Position(pawn.position.row + direction, pawn.position.col - 1),
            Position(pawn.position.row + direction, pawn.position.col + 1)
        )

        captureMoves.forEach { move ->
            if (isValidPosition(move)) {
                val targetPiece = board[move.row][move.col]
                if (targetPiece != null && targetPiece.player != pawn.player) {
                    moves.add(move)
                }
                // 吃过路兵逻辑需要在外部处理
            }
        }

        return moves
    }

    private fun calculateRookMoves(
        rook: ChessPiece,
        board: List<List<ChessPiece?>>
    ): List<Position> {
        val moves = mutableListOf<Position>()
        val directions = listOf(
            Position(-1, 0), Position(1, 0), Position(0, -1), Position(0, 1)
        )

        directions.forEach { direction ->
            var currentRow = rook.position.row + direction.row
            var currentCol = rook.position.col + direction.col

            while (isValidPosition(Position(currentRow, currentCol))) {
                val targetPiece = board[currentRow][currentCol]
                if (targetPiece == null) {
                    moves.add(Position(currentRow, currentCol))
                } else {
                    if (targetPiece.player != rook.player) {
                        moves.add(Position(currentRow, currentCol))
                    }
                    break
                }
                currentRow += direction.row
                currentCol += direction.col
            }
        }

        return moves
    }

    private fun calculateKnightMoves(
        knight: ChessPiece,
        board: List<List<ChessPiece?>>
    ): List<Position> {
        val moves = mutableListOf<Position>()
        val knightMoves = listOf(
            Position(-2, -1), Position(-2, 1),
            Position(-1, -2), Position(-1, 2),
            Position(1, -2), Position(1, 2),
            Position(2, -1), Position(2, 1)
        )

        knightMoves.forEach { move ->
            val newRow = knight.position.row + move.row
            val newCol = knight.position.col + move.col
            val newPosition = Position(newRow, newCol)

            if (isValidPosition(newPosition)) {
                val targetPiece = board[newRow][newCol]
                if (targetPiece == null || targetPiece.player != knight.player) {
                    moves.add(newPosition)
                }
            }
        }

        return moves
    }

    private fun calculateBishopMoves(
        bishop: ChessPiece,
        board: List<List<ChessPiece?>>
    ): List<Position> {
        val moves = mutableListOf<Position>()
        val directions = listOf(
            Position(-1, -1), Position(-1, 1), Position(1, -1), Position(1, 1)
        )

        directions.forEach { direction ->
            var currentRow = bishop.position.row + direction.row
            var currentCol = bishop.position.col + direction.col

            while (isValidPosition(Position(currentRow, currentCol))) {
                val targetPiece = board[currentRow][currentCol]
                if (targetPiece == null) {
                    moves.add(Position(currentRow, currentCol))
                } else {
                    if (targetPiece.player != bishop.player) {
                        moves.add(Position(currentRow, currentCol))
                    }
                    break
                }
                currentRow += direction.row
                currentCol += direction.col
            }
        }

        return moves
    }

    private fun calculateQueenMoves(
        queen: ChessPiece,
        board: List<List<ChessPiece?>>
    ): List<Position> {
        return calculateRookMoves(queen, board) + calculateBishopMoves(queen, board)
    }

    private fun calculateKingMoves(
        king: ChessPiece,
        board: List<List<ChessPiece?>>
    ): List<Position> {
        val moves = mutableListOf<Position>()
        val directions = listOf(
            Position(-1, -1), Position(-1, 0), Position(-1, 1),
            Position(0, -1), Position(0, 1),
            Position(1, -1), Position(1, 0), Position(1, 1)
        )

        directions.forEach { direction ->
            val newRow = king.position.row + direction.row
            val newCol = king.position.col + direction.col
            val newPosition = Position(newRow, newCol)

            if (isValidPosition(newPosition)) {
                val targetPiece = board[newRow][newCol]
                if (targetPiece == null || targetPiece.player != king.player) {
                    if (!wouldBeInCheck(king, newPosition, board)) {
                        moves.add(newPosition)
                    }
                }
            }
        }

        // 王车易位 - 修复后的逻辑
        if (!isInCheck(king.player, board)) {
            // 短易位（王翼易位）
            if (canCastleKingside(king, board)) {
                val kingsideMove = Position(king.position.row, king.position.col + 2)
                if (!wouldBeInCheck(king, kingsideMove, board)) {
                    moves.add(kingsideMove)
                }
            }
            // 长易位（后翼易位）
            if (canCastleQueenside(king, board)) {
                val queensideMove = Position(king.position.row, king.position.col - 2)
                if (!wouldBeInCheck(king, queensideMove, board)) {
                    moves.add(queensideMove)
                }
            }
        }

        return moves
    }

    private fun isValidMove(
        piece: ChessPiece,
        target: Position,
        board: List<List<ChessPiece?>>
    ): Boolean {
        if (!isValidPosition(target)) return false

        val targetPiece = board[target.row][target.col]

        // 允许吃任何敌方棋子，包括王
        if (targetPiece != null && targetPiece.player == piece.player) return false

        if (piece.type == PieceType.KING) {
            return !wouldBeInCheck(piece, target, board)
        }

        return true
    }

    private fun wouldBeInCheck(
        piece: ChessPiece,
        newPosition: Position,
        board: List<List<ChessPiece?>>
    ): Boolean {
        val tempBoard = board.map { it.toMutableList() }.toMutableList()
        tempBoard[newPosition.row][newPosition.col] = piece.copy(position = newPosition)
        tempBoard[piece.position.row][piece.position.col] = null

        return isInCheck(piece.player, tempBoard)
    }

    private fun isInCheck(player: Player, board: List<List<ChessPiece?>>): Boolean {
        val kingPosition = findKingPosition(player, board) ?: return false

        for (row in 0 until 8) {
            for (col in 0 until 8) {
                val piece = board[row][col]
                if (piece != null && piece.player != player) {
                    val moves = calculateValidMovesWithoutCheck(piece, board)
                    if (moves.any { it.row == kingPosition.row && it.col == kingPosition.col }) {
                        return true
                    }
                }
            }
        }

        return false
    }

    private fun calculateValidMovesWithoutCheck(
        piece: ChessPiece,
        board: List<List<ChessPiece?>>
    ): List<Position> {
        return when (piece.type) {
            PieceType.PAWN -> calculatePawnMoves(piece, board)
            PieceType.ROOK -> calculateRookMoves(piece, board)
            PieceType.KNIGHT -> calculateKnightMoves(piece, board)
            PieceType.BISHOP -> calculateBishopMoves(piece, board)
            PieceType.QUEEN -> calculateQueenMoves(piece, board)
            PieceType.KING -> calculateKingMovesWithoutCheck(piece, board)
        }.filter {
            isValidPosition(it) &&
                    (board[it.row][it.col] == null || board[it.row][it.col]?.player != piece.player)
        }
    }

    private fun calculateKingMovesWithoutCheck(
        king: ChessPiece,
        board: List<List<ChessPiece?>>
    ): List<Position> {
        val moves = mutableListOf<Position>()
        val directions = listOf(
            Position(-1, -1), Position(-1, 0), Position(-1, 1),
            Position(0, -1), Position(0, 1),
            Position(1, -1), Position(1, 0), Position(1, 1)
        )

        directions.forEach { direction ->
            val newRow = king.position.row + direction.row
            val newCol = king.position.col + direction.col
            val newPosition = Position(newRow, newCol)

            if (isValidPosition(newPosition)) {
                val targetPiece = board[newRow][newCol]
                if (targetPiece == null || targetPiece.player != king.player) {
                    moves.add(newPosition)
                }
            }
        }

        return moves
    }

    private fun findKingPosition(player: Player, board: List<List<ChessPiece?>>): Position? {
        for (row in 0 until 8) {
            for (col in 0 until 8) {
                val piece = board[row][col]
                if (piece != null && piece.type == PieceType.KING && piece.player == player) {
                    return Position(row, col)
                }
            }
        }
        return null
    }

    private fun canCastleKingside(king: ChessPiece, board: List<List<ChessPiece?>>): Boolean {
        val castleKey = if (king.player == Player.WHITE) "whiteKingside" else "blackKingside"

        // 检查易位权利
        if (!castlingRights[castleKey]!!) return false

        // 检查王是否在初始位置
        val expectedRow = if (king.player == Player.WHITE) 7 else 0
        if (king.position.row != expectedRow || king.position.col != 4) return false

        // 重要：检查王当前是否被将军
        if (isInCheck(king.player, board)) return false

        // 检查车是否存在且未移动
        val rookCol = 7
        val rook = board[expectedRow][rookCol]
        if (rook == null || rook.type != PieceType.ROOK || rook.player != king.player) return false

        // 检查王和车之间的格子是否为空（f1和g1）
        for (col in 5..6) {
            if (board[expectedRow][col] != null) return false
        }

        // 检查王经过的格子是否安全（e1, f1, g1）
        val attackedSquares = listOf(4, 5, 6)
        for (col in attackedSquares) {
            if (isSquareAttacked(Position(expectedRow, col), king.player.opponent(), board)) {
                return false
            }
        }

        return true
    }

    private fun canCastleQueenside(king: ChessPiece, board: List<List<ChessPiece?>>): Boolean {
        val castleKey = if (king.player == Player.WHITE) "whiteQueenside" else "blackQueenside"

        if (!castlingRights[castleKey]!!) return false

        val expectedRow = if (king.player == Player.WHITE) 7 else 0
        if (king.position.row != expectedRow || king.position.col != 4) return false

        // 重要：检查王当前是否被将军
        if (isInCheck(king.player, board)) return false

        // 检查车
        val rookCol = 0
        val rook = board[expectedRow][rookCol]
        if (rook == null || rook.type != PieceType.ROOK || rook.player != king.player) return false

        // 修复：只检查b1, c1, d1是否为空（不包括a1）
        for (col in 1..3) {
            if (board[expectedRow][col] != null) return false
        }

        // 检查王经过的格子是否安全（c1, d1, e1）
        val attackedSquares = listOf(2, 3, 4)
        for (col in attackedSquares) {
            if (isSquareAttacked(Position(expectedRow, col), king.player.opponent(), board)) {
                return false
            }
        }

        return true
    }

    private fun isSquareAttacked(
        square: Position,
        byPlayer: Player,
        board: List<List<ChessPiece?>>
    ): Boolean {
        for (row in 0 until 8) {
            for (col in 0 until 8) {
                val piece = board[row][col]
                if (piece != null && piece.player == byPlayer) {
                    val moves = calculateValidMovesWithoutCheck(piece, board)
                    if (moves.any { it.row == square.row && it.col == square.col }) {
                        return true
                    }
                }
            }
        }
        return false
    }

    private fun getDisambiguation(
        piece: ChessPiece,
        from: Position,
        to: Position,
        board: List<List<ChessPiece?>>
    ): String {
        val sameTypePieces = mutableListOf<ChessPiece>()

        for (row in 0 until 8) {
            for (col in 0 until 8) {
                val otherPiece = board[row][col]
                if (otherPiece != null &&
                    otherPiece.type == piece.type &&
                    otherPiece.player == piece.player &&
                    !(row == from.row && col == from.col)
                ) {
                    sameTypePieces.add(otherPiece)
                }
            }
        }

        if (sameTypePieces.isEmpty()) return ""

        val ambiguousPieces = sameTypePieces.filter { otherPiece ->
            calculateValidMoves(otherPiece, board).any { it.row == to.row && it.col == to.col }
        }

        if (ambiguousPieces.isEmpty()) return ""

        val sameFile = ambiguousPieces.any { it.position.col == from.col }
        val sameRank = ambiguousPieces.any { it.position.row == from.row }

        return when {
            !sameFile -> getFileLetter(from.col)
            !sameRank -> "${8 - from.row}"
            else -> "${getFileLetter(from.col)}${8 - from.row}"
        }
    }

    private fun getFileLetter(col: Int): String {
        return listOf("a", "b", "c", "d", "e", "f", "g", "h")[col]
    }

    private fun isValidPosition(position: Position): Boolean {
        return position.row in 0..7 && position.col in 0..7
    }

    private fun initialBoardState(): List<List<ChessPiece?>> {
        val emptyRow = List<ChessPiece?>(8) { null }

        return listOf(
            // 第0行 - 黑方
            listOf(
                ChessPiece(PieceType.ROOK, Player.BLACK, Position(0, 0)),
                ChessPiece(PieceType.KNIGHT, Player.BLACK, Position(0, 1)),
                ChessPiece(PieceType.BISHOP, Player.BLACK, Position(0, 2)),
                ChessPiece(PieceType.QUEEN, Player.BLACK, Position(0, 3)),
                ChessPiece(PieceType.KING, Player.BLACK, Position(0, 4)),
                ChessPiece(PieceType.BISHOP, Player.BLACK, Position(0, 5)),
                ChessPiece(PieceType.KNIGHT, Player.BLACK, Position(0, 6)),
                ChessPiece(PieceType.ROOK, Player.BLACK, Position(0, 7))
            ),
            // 第1行 - 黑兵
            List(8) { col -> ChessPiece(PieceType.PAWN, Player.BLACK, Position(1, col)) },
            // 第2-5行 - 空
            emptyRow, emptyRow, emptyRow, emptyRow,
            // 第6行 - 白兵
            List(8) { col -> ChessPiece(PieceType.PAWN, Player.WHITE, Position(6, col)) },
            // 第7行 - 白方
            listOf(
                ChessPiece(PieceType.ROOK, Player.WHITE, Position(7, 0)),
                ChessPiece(PieceType.KNIGHT, Player.WHITE, Position(7, 1)),
                ChessPiece(PieceType.BISHOP, Player.WHITE, Position(7, 2)),
                ChessPiece(PieceType.QUEEN, Player.WHITE, Position(7, 3)),
                ChessPiece(PieceType.KING, Player.WHITE, Position(7, 4)),
                ChessPiece(PieceType.BISHOP, Player.WHITE, Position(7, 5)),
                ChessPiece(PieceType.KNIGHT, Player.WHITE, Position(7, 6)),
                ChessPiece(PieceType.ROOK, Player.WHITE, Position(7, 7))
            )
        )
    }
}

// 数据类和扩展函数
data class MoveResult(
    val enPassantTarget: Position?,
    val isCapture: Boolean,
    val isKingCaptured: Boolean = false
)

data class GameSnapshot(
    val boardState: List<List<ChessPiece?>>,
    val currentTurn: Player,
    val moveCount: Int,
    val moveHistory: List<ChessMove>,
    val gameStatus: GameStatus,
    val enPassantTarget: Position?,
    val halfMoveClock: Int,
    val fullMoveNumber: Int,
    val castlingWhiteKingside: Boolean,
    val castlingWhiteQueenside: Boolean,
    val castlingBlackKingside: Boolean,
    val castlingBlackQueenside: Boolean,
    val highlightedMove: Pair<Position, Position>? = null // 确保这里也有
)

fun Player.opponent(): Player {
    return if (this == Player.WHITE) Player.BLACK else Player.WHITE
}


